package com.celesea.auth.menu.service;

import com.celesea.auth.menu.dao.MenuDao;
import com.celesea.auth.menu.entity.Menu;
import com.celesea.auth.menu.vo.MenuFilter;
import com.celesea.auth.menu.vo.MenuTreeVo;
import com.celesea.auth.menu.vo.MenuVo;
import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.CollectionKit;
import com.celesea.framework.util.Const;
import com.celesea.framework.util.tree.TreeUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ${DESCRIPTION}
 *
 * @author JackYuan
 * @create 2017-10-25 20:53
 */
@Service
public class MenuServiceImpl extends AbstractBaseService<Menu> implements MenuService {

    @Autowired
    private MenuDao menuDao;

    /**
     * 查询完整树结构
     *
     * @return
     */
    @Override
    public Map<String, List<MenuVo>> selectMenus() {
        // TODO 缓存优化
        Map<String, List<MenuVo>> results = Maps.newHashMap();
        MenuFilter filter = new MenuFilter(Const.StatusFlag.ENABLE);
        filter.setMenuFlag(Const.Bool.TRUE);
        List<Menu> lists = menuDao.selectUserMenus(filter);
        if (CollectionKit.isNotEmpty(lists)) {
            Map<String, MenuVo> maps = Maps.newHashMap();
            Iterator<Menu> iterator = lists.iterator();
            while (iterator.hasNext()) {
                Menu menu = iterator.next();
                MenuVo menuVo = new MenuVo(menu);
                if (Const.Bool.isTrue(menu.getLeaf())) {
                    MenuVo parent = maps.get(menu.getParentId());
                    parent.getChildren().add(menuVo);
                } else {
                    maps.put(menu.getId(), menuVo);
                    List<MenuVo> firsts = results.get(menu.getModule());
                    if (firsts == null) {
                        firsts = Lists.newArrayList();
                        results.put(menu.getModule(), firsts);
                    }
                    firsts.add(menuVo);
                }
            }
        }
        return results;
    }

    @Override
    public List<MenuTreeVo> selectPermissions() {
        List<Menu> lists = menuDao.selectMenus(new MenuFilter(Const.StatusFlag.ENABLE));
        List<MenuTreeVo> trees = lists.stream().map(item -> new MenuTreeVo(item))
                .collect(Collectors.toList());
        return TreeUtil.build2Tree(trees,null);
    }
}
